# -*- coding: utf-8 -*-
# @time: 2024/6/6 16:57
# @file: diffusion_index
# @author: tyshixi08

from get_data.covprice_mid import *

# 计算转债收盘价滚动五天为正的转债占比
def positive_return_5D_pct(code=code_ls(), start_date = month_ls()[0].replace('-','') + '01', end_date = month_ls()[-1].replace('-','') + '01'):
    df = get_bond_price(code, start_date, end_date)
    df['date'] = pd.to_datetime(df['date'])
    df.sort_values(by=['order_book_id', 'date'], inplace=True)

    df['close_5D_ago'] = df.groupby('order_book_id')['close'].transform(lambda x: x.shift(5))
    df = df.dropna()
    df['higher_than_5D_ago'] = (df['close'] > df['close_5D_ago']).astype(int)
    df = df.reset_index(drop=True)
    df_all = df.groupby('date')['order_book_id'].count().reset_index()
    df_positive_return_5D_num = df.groupby('date')['higher_than_5D_ago'].sum().reset_index()
    df = pd.merge(df_positive_return_5D_num, df_all, how = 'outer', on = 'date')
    df['cov_+ret_pct_5D'] = df['higher_than_5D_ago'] / df['order_book_id']
    return df[['date', 'cov_+ret_pct_5D']].sort_values('date')

# 数据存档
def cov_positive_ret_pct_save():
    excel_file_path = 'cov_+ret_pct_5D.csv'
    #if os.path.exists('原始数据/' + excel_file_path):
    #    df = pd.read_csv('原始数据/' + excel_file_path)
    #    return df
    #else:
    save_CSV(positive_return_5D_pct(), 'get_data/原始数据/' + excel_file_path.split('.')[0])
    df = pd.read_csv('get_data/原始数据/' + excel_file_path)
    return df
